class EventEmitter {
  handlers = {};
  // 添加事件
  on(type, callback, once = false) {
    if (!this.handlers[type]) {
      this.handlers[type] = [];
    }

    if (!this.handlers[type].includes(callback)) {
      this.handlers[type].push(callback);
      callback.once = once;
    }
  }

  // 只执行一次的事件
  once(type, callback) {
    this.on(type, callback, true);
  }

  off(type, callback) {
    if (this.handlers[type]) {
      this.handlers[type] = this.handlers[type].filter(elem => callback !== elem);
    }
  }

  trigger(type) {
    if (this.handlers[type]) {
      this.handlers[type].forEach(elem => {
        elem();

        if (elem.once) {
          this.off(type, elem);
        }
      });
    }
  }
}

const test = new EventEmitter();

test.on('click', () => {
  console.log('test1');
})

test.once('click', () => {
  console.log('test2');
})

test.on('click', () => {
  console.log('test3');
})

test.trigger('click');
test.trigger('click');
